package com.work.yshop.ui.activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.work.yshop.R;
import com.work.yshop.adapter.ProductAdapter;
import com.work.yshop.model.Product;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的商品页面
 */
public class MyProductsActivity extends AppCompatActivity {
    
    private static final int REQUEST_ADD_PRODUCT = 100;
    private static final int REQUEST_EDIT_PRODUCT = 101;
    
    private ImageView btnBack;
    private ImageView btnAdd;
    private EditText etSearch;
    private TabLayout tabLayout;
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private LinearLayout emptyView;
    private FloatingActionButton fabAdd;
    
    private ProductAdapter adapter;
    private List<Product> productList = new ArrayList<>();
    
    // 当前选中的状态标签，0-全部，1-已上架，2-已下架，3-售罄
    private int currentTabIndex = 0;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_products);
        
        initViews();
        setupRecyclerView();
        setupListeners();
        
        // 加载商品数据
        loadProducts();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnAdd = findViewById(R.id.btn_add);
        etSearch = findViewById(R.id.et_search);
        tabLayout = findViewById(R.id.tab_layout);
        swipeRefresh = findViewById(R.id.swipe_refresh);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);
        fabAdd = findViewById(R.id.fab_add);
    }
    
    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ProductAdapter(this, productList);
        recyclerView.setAdapter(adapter);
        
        // 设置编辑商品点击事件
        adapter.setOnEditClickListener(position -> {
            Product product = productList.get(position);
            Intent intent = new Intent(MyProductsActivity.this, ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            startActivityForResult(intent, REQUEST_EDIT_PRODUCT);
        });
        
        // 设置切换商品状态点击事件
        adapter.setOnToggleStatusClickListener(position -> {
            Product product = productList.get(position);
            toggleProductStatus(product);
        });
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> onBackPressed());
        
        btnAdd.setOnClickListener(v -> {
            Intent intent = new Intent(MyProductsActivity.this, PublishProductActivity.class);
            startActivityForResult(intent, REQUEST_ADD_PRODUCT);
        });
        
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(MyProductsActivity.this, PublishProductActivity.class);
            startActivityForResult(intent, REQUEST_ADD_PRODUCT);
        });
        
        // 下拉刷新
        swipeRefresh.setOnRefreshListener(this::loadProducts);
        
        // 标签切换
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentTabIndex = tab.getPosition();
                loadProducts();
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });
        
        // 搜索框文本变化监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要处理
            }
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要处理
            }
            
            @Override
            public void afterTextChanged(Editable s) {
                // 搜索商品
                searchProducts(s.toString());
            }
        });
    }
    
    /**
     * 加载商品数据
     */
    private void loadProducts() {
        String selection;
        String[] selectionArgs;
        
        int userId = UserSession.getInstance().getUserId();
        int userType = UserSession.getInstance().getUserType();
        
        // 根据标签筛选
        switch (currentTabIndex) {
            case 1: // 已上架
                selection = "user_id = ? AND user_type = ? AND status = 1";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType)};
                break;
            case 2: // 已下架
                selection = "user_id = ? AND user_type = ? AND status = 0";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType)};
                break;
            case 3: // 售罄
                selection = "user_id = ? AND user_type = ? AND stock = 0";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType)};
                break;
            default: // 全部
                selection = "user_id = ? AND user_type = ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType)};
                break;
        }
        
        Cursor cursor = getContentResolver().query(
                ProductProvider.CONTENT_URI,
                null,
                selection,
                selectionArgs,
                "update_date DESC"
        );
        
        productList.clear();
        
        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = cursorToProduct(cursor);
                    productList.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        
        updateUI();
    }
    
    /**
     * 搜索商品
     */
    private void searchProducts(String keyword) {
        if (keyword.isEmpty()) {
            loadProducts();
            return;
        }
        
        String selection;
        String[] selectionArgs;
        
        int userId = UserSession.getInstance().getUserId();
        int userType = UserSession.getInstance().getUserType();
        
        // 根据标签和关键词筛选
        switch (currentTabIndex) {
            case 1: // 已上架
                selection = "user_id = ? AND user_type = ? AND status = 1 AND name LIKE ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType), "%" + keyword + "%"};
                break;
            case 2: // 已下架
                selection = "user_id = ? AND user_type = ? AND status = 0 AND name LIKE ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType), "%" + keyword + "%"};
                break;
            case 3: // 售罄
                selection = "user_id = ? AND user_type = ? AND stock = 0 AND name LIKE ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType), "%" + keyword + "%"};
                break;
            default: // 全部
                selection = "user_id = ? AND user_type = ? AND name LIKE ?";
                selectionArgs = new String[]{String.valueOf(userId), String.valueOf(userType), "%" + keyword + "%"};
                break;
        }
        
        Cursor cursor = getContentResolver().query(
                ProductProvider.CONTENT_URI,
                null,
                selection,
                selectionArgs,
                "update_date DESC"
        );
        
        productList.clear();
        
        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = cursorToProduct(cursor);
                    productList.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        
        updateUI();
    }
    
    /**
     * 将Cursor转换为Product对象
     */
    private Product cursorToProduct(Cursor cursor) {
        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
        double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
        int stock = cursor.getInt(cursor.getColumnIndexOrThrow("stock"));
        String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
        String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));
        String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
        int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
        String publishDate = cursor.getString(cursor.getColumnIndexOrThrow("publish_date"));
        String updateDate = cursor.getString(cursor.getColumnIndexOrThrow("update_date"));
        
        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setPrice(price);
        product.setStock(stock);
        product.setDescription(description);
        product.setCategory(category);
        product.setImageUrl(imageUrl);
        product.setStatus(status);
        product.setPublishDate(publishDate);
        product.setUpdateDate(updateDate);
        
        return product;
    }
    
    /**
     * 切换商品上架/下架状态
     */
    private void toggleProductStatus(Product product) {
        // 切换状态
        int newStatus = product.getStatus() == 1 ? 0 : 1;
        
        // 更新数据库
        android.content.ContentValues values = new android.content.ContentValues();
        values.put("status", newStatus);
        
        int count = getContentResolver().update(
                ProductProvider.CONTENT_URI,
                values,
                "_id = ?",
                new String[]{String.valueOf(product.getId())}
        );
        
        if (count > 0) {
            Toast.makeText(this, newStatus == 1 ? "商品已上架" : "商品已下架", Toast.LENGTH_SHORT).show();
            loadProducts();
        } else {
            Toast.makeText(this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 更新UI
     */
    private void updateUI() {
        if (swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
        
        adapter.notifyDataSetChanged();
        
        if (productList.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if ((requestCode == REQUEST_ADD_PRODUCT || requestCode == REQUEST_EDIT_PRODUCT) && resultCode == RESULT_OK) {
            loadProducts();
        }
    }
} 